/*
 ============================================================================
 Name        : main.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Webcam readout
 ============================================================================
 */

#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include "termios.h"
#include "protocol.h"
#include "string.h"
#include "video.h"
#include "messages.h"

int open_serial(char* line);

int main()
{
   int fd;
   SerialConn conn;
   conn.state = START;
   char* line = "/dev/ttyO0";
   fd = open_serial(line); //open serial connection
   conn.fd = fd;
   unsigned char rxBuffer[1];
   int ret;

   if (fd)
   {
      //get_position(&conn);
      //reset(&conn);

      set_position(&conn, SET_HORIZONTAL, 0);
      set_position(&conn, SET_VERTICAL, 0);

      start_video(&conn); // this function never returns
      // uncomment previous line to start outputting a sinus

      double step = 0.01;
      double i = 0;
      double last_out = 0;
      while (1)
      {
         double out = 0.5 * sin(i);
         set_position(&conn, SET_HORIZONTAL_DIFF, out - last_out);
         set_position(&conn, SET_VERTICAL_DIFF, out - last_out);
         i += step;
         last_out = out;
         ret = read(fd, &rxBuffer, 1);
         usleep(10000);
      }
      set_position(&conn, SET_HORIZONTAL, 0);
      set_position(&conn, SET_VERTICAL, 0);

   }

   close(fd);
}

/* Opens serial connection */
int open_serial(char* line)
{
   int fd;
   struct termios tty_attributes;

   if ((fd = open(line, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
   {
      fprintf(stderr, "Open error on \n");
      return 0;
   }
   else
   {
      tcgetattr(fd, &tty_attributes);
      cfmakeraw(&tty_attributes);
      cfsetispeed(&tty_attributes, 115200);
      cfsetospeed(&tty_attributes, 115200);
      tcsetattr(fd, TCSANOW, &tty_attributes);

      return fd;
   }
}


